package com.ruoyi.intelligence.chat.baidu;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.intelligence.chat.baidu.config.BdProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wxj
 * @Date: 2023/11/23
 */
@Slf4j
@Component
public class SerBFactory {

    @Resource
    private BdProperties bdProperties;
   private final static   String tokenUrl="https://aip.baidubce.com/oauth/2.0/token";
   private final static   String stableUrl="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/text2image/sd_xl";
   private final static   String ERNIEBot4Url="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro";



    public String getAccessToken() {
        String accessToken = RedisUtils.getCacheObject("BDYAccessToken");
        if (ObjectUtil.isNotEmpty(accessToken)){
            return accessToken;
        }
        //链式构建请求
        String result = HttpRequest.get(tokenUrl+"?grant_type=client_credentials&client_id="+bdProperties.getApiKey()+"&client_secret="+bdProperties.getSecretKey()+"")
            .timeout(20000)
            .execute().body();
        log.info("打印获取token：{}",JsonUtils.toJsonString(result));
        JSONObject entries = JsonUtils.parseObject(result, JSONObject.class);
        accessToken = (String) entries.get("access_token");
        Integer expires_in = (Integer) entries.get("expires_in");
        RedisUtils.setCacheObject("BDYRefreshToken",accessToken,  Duration.ofSeconds(expires_in));
        return accessToken;
    }
    /**
     * Stable-Diffusion-XL
     * 调用本接口，根据用户输入的文本生成图片
     */
    public List<JSONObject>  stable(String msg){
        Map<String, Object> map = new HashMap<>();
        map.put("prompt",msg);
        map.put("size","1024x1024");
        map.put("n",1);
        //System.out.println(stableUrl+"?access_token="+getAccessToken()+" -d "+"'"+JsonUtils.toJsonString(map)+"'");
        String result = HttpRequest.post(stableUrl+"?access_token="+getAccessToken())
            .body(JsonUtils.toJsonString(map))
            .timeout(20000)
            .execute().body();
        log.info("打印结果：{}",JsonUtils.toJsonString(result));
        JSONObject entries = JsonUtils.parseObject(result, JSONObject.class);
        List<JSONObject> resultStr = (List<JSONObject>) entries.get("data");
        return resultStr;

    }

    /***
     * ERNIE-Bot 4.0是百度自行研发的大语言模型，覆盖海量中文数据，具有更强的对话问答、内容创作生成等能力。
     */

    public  String ERNIEBot4(List<String> msgs){
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> objects = new ArrayList<>();
        for (int i=0;i<msgs.size();i++){
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("role",i%2==0?"user":"assistant");
            stringMap.put("content",msgs.get(i));
            objects.add(stringMap);
        }
        map.put("messages",objects);
        /***
         *  (1）较高的数值会使输出更加随机，而较低的数值会使其更加集中和确定
         * （2）默认0.8，范围 (0, 1.0]，不能为0
         * （3）建议该参数和top_p只设置1个
         * （4）建议top_p和temperature不要同时更改
         */
        map.put("temperature",0.8);
        map.put("n",4);
        //System.out.println(stableUrl+"?access_token="+getAccessToken()+" -d "+"'"+JsonUtils.toJsonString(map)+"'");
        String result = HttpRequest.post(ERNIEBot4Url+"?access_token="+getAccessToken())
            .body(JsonUtils.toJsonString(map))
            .timeout(20000)
            .execute().body();
        log.info("打印结果：{}",JsonUtils.toJsonString(result));
        JSONObject entries = JsonUtils.parseObject(result, JSONObject.class);
        String resultStr = (String) entries.get("result");
        return resultStr;
    }

}
